package com.starhub.application.collection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starhub.application.collection.entity.KnowledgeCollection;
import com.starhub.application.collection.mapper.KnowledgeCollectionMapper;
import com.starhub.application.collection.service.KnowledgeCollectionService;

import com.starhub.utils.Util;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 知识库表服务实现类
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-09
 */
@Slf4j
@Service
public class KnowledgeCollectionServiceImpl extends ServiceImpl<KnowledgeCollectionMapper, KnowledgeCollection> implements KnowledgeCollectionService {

    private final KnowledgeCollectionMapper knowledgeCollectionMapper;

    public KnowledgeCollectionServiceImpl(KnowledgeCollectionMapper knowledgeCollectionMapper) {
        this.knowledgeCollectionMapper = knowledgeCollectionMapper;
    }

    @Override
    public int insert(KnowledgeCollection knowledgeCollection) {
        return knowledgeCollectionMapper.insert(knowledgeCollection);
    }

    @Override
    public boolean updateById(KnowledgeCollection knowledgeCollection) {
        return knowledgeCollectionMapper.updateById(knowledgeCollection) > 0;
    }

    @Override
    public KnowledgeCollection selectByIdentifier(String collectionIdentifier) {
        LambdaQueryWrapper<KnowledgeCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KnowledgeCollection::getCollectionIdentifier, collectionIdentifier)
                .eq(KnowledgeCollection::getDeleteType, 0);
        return knowledgeCollectionMapper.selectOne(queryWrapper);
    }

    @Override
    public long countByIdentifier(String collectionIdentifier) {
        LambdaQueryWrapper<KnowledgeCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KnowledgeCollection::getCollectionIdentifier, collectionIdentifier)
                .eq(KnowledgeCollection::getDeleteType, 0);
        return knowledgeCollectionMapper.selectCount(queryWrapper);
    }

    @Override
    public KnowledgeCollection selectById(Long id) {
        return knowledgeCollectionMapper.selectById(id);
    }

    @Override
    public KnowledgeCollection selectByIdAndNotDeleted(Long id) {
        LambdaQueryWrapper<KnowledgeCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KnowledgeCollection::getId, id)
                .eq(KnowledgeCollection::getDeleteType, 0);
        return knowledgeCollectionMapper.selectOne(queryWrapper);
    }

    @Override
    public List<KnowledgeCollection> selectBatchIds(List<Long> ids) {
        return this.listByIds(ids);
    }

    @Override
    public String getDataIdByContent(String content, Long collectionId) {
        if (content == null || content.trim().isEmpty() || collectionId == null) {
            return null;
        }

        try {
            // 根据集合ID获取集合信息
            KnowledgeCollection collection = this.selectById(collectionId);
            if (collection == null) {
                log.warn("Collection not found with id: {}", collectionId);
                return null;
            }

            // 根据不同的存储类型进行查询
            switch (collection.getMetaStorageType()) {
                case 0: // 数据库存储
                    return queryDataIdFromDatabase(content, collection);
                case 1: // 向量存储
                    return queryDataIdFromVector(content, collection);
                default:
                    log.warn("Unsupported storage type: {}", collection.getMetaStorageType());
                    return null;
            }
        } catch (Exception e) {
            log.error("Failed to get data ID by content: {} in collection: {}", content, collectionId, e);
            return null;
        }
    }

    /**
     * 从数据库存储中查询数据ID
     * @param content 文本内容
     * @param collection 集合信息
     * @return 数据ID
     */
    private String queryDataIdFromDatabase(String content, KnowledgeCollection collection) {
        try {
            // 使用Mapper直接查询数据库
            // 这里需要根据实际的表结构来实现
            // 可以通过collection.getCollectionIdentifier()来确定表名

            String tableName = collection.getCollectionIdentifier();
            if (tableName == null || tableName.trim().isEmpty()) {
                log.warn("Collection identifier is null or empty for collection: {}", collection.getId());
                return null;
            }

            // 调用Mapper的查询方法
            return knowledgeCollectionMapper.queryDataIdByContent(content, collection.getId(), tableName);

        } catch (Exception e) {
            log.error("Failed to query data ID from database: {}", content, e);
            return null;
        }
    }

    /**
     * 从向量存储中查询数据ID
     * @param content 文本内容
     * @param collection 集合信息
     * @return 数据ID
     */
    private String queryDataIdFromVector(String content, KnowledgeCollection collection) {
        try {
            // 这里需要调用向量存储的查询方法
            // 可能需要使用Milvus或其他向量数据库的API
            // 示例实现，需要根据实际情况调整

            // 可以调用MilvusStore或其他向量存储服务
            // return milvusStore.queryDataIdByContent(content, collection.getCollectionIdentifier());

            log.info("Vector storage query not implemented yet for content: {} in collection: {}",
                    content, collection.getCollectionIdentifier());
            return null;
        } catch (Exception e) {
            log.error("Failed to query data ID from vector storage: {}", content, e);
            return null;
        }
    }

    @Override
    public int deleteById(Long id) {

        KnowledgeCollection knowledgeCollection = new KnowledgeCollection();
        knowledgeCollection.setDeleteType(1);
        knowledgeCollection.setId(id);
        return knowledgeCollectionMapper.updateById(knowledgeCollection);
    }


    @Override
    public int deleteRecord(Long id) {
        return knowledgeCollectionMapper.deleteById(id);
    }

    @Override
    public List<KnowledgeCollection> selectByMap(Map<String, Object> params) {

        String baseId = Util.null2String(params.get("baseId"));
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("delete_type",0);
        if(StringUtils.isNotEmpty(baseId)){
            columnMap.put("base_id",baseId);
        }
        return knowledgeCollectionMapper.selectByMap(columnMap);
    }


    @Override
    public List<KnowledgeCollection> getActiveKnowledgeCollection(Map<String, Object> params) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("delete_type",0);
        return knowledgeCollectionMapper.selectByMap(columnMap);
    }
}